package net.newsmth.smthapp.android.helper;

import net.newsmth.smthapp.android.config.SmthConnection;
import net.newsmth.smthapp.android.config.SmthNetStatusType;
import net.newsmth.smthapp.android.config.AppSettings;
import net.newsmth.smthapp.android.model.Account;


/**
 * Created by Hatsune Miku on 4/2/14.
 */
public class AccountHelperImpl implements AccountHelper {
    private AppSettings appSettings;
    private SmthConnection conn;

    public AccountHelperImpl() {}

    public AccountHelperImpl(AppSettings settings, SmthConnection conn) {
        this.appSettings = settings;
        this.conn = conn;
    }

    public AppSettings getSettings() {
        return appSettings;
    }

    public void setSettings(AppSettings settings) {
        this.appSettings = settings;
    }

    //region Override parents


    @Override
    public boolean loginAndSave(Account account) {
        boolean result = this.loginByPassword(account.getUserName(), account.getPassword());

        if (result) {
            appSettings.setUserName(account.getUserName());
            appSettings.setToken(conn.getToken());
        }

        return result;
    }

    private boolean loginByPassword(String userName, String password) {
        return conn.login(userName, password);
    }

    private boolean loginByToken(String token) {
        conn.login(token);

        return conn.getErrorType() == SmthNetStatusType.OK;
    }

    /**
     * login by password if password is not null or login in by token
     * @param account User account for login
     * @return if login success, return true.
     */
    @Override
    public boolean login(Account account) {
        boolean returnValue = false;

        String password = account.getPassword();
        if (password != null &&  !password.isEmpty()) {
            returnValue = loginByPassword(account.getUserName(), password);
        } else {
            returnValue = loginByToken(account.getToken());
        }

        return  returnValue;
    }

    @Override
    public void logout() {
        conn.logout();
        appSettings.setToken("");
    }

    @Override
    public Account loadAccount() {
        Account account = new Account();
        account.setUserName(appSettings.getUserName());
        account.setToken(appSettings.getToken());

        return account;
    }
    //endregion

}
